<?php

namespace app\service;

use app\model\MemberVip;

class MemberVipService
{
    private $memberVip;

    public function __construct()
    {
        $this->memberVip = new MemberVip();
    }

    /**
     * 获取会员VIP列表
     *
     * @param array $params 查询参数
     * @return \think\Paginator
     */
    public function list($params = [])
    {
        $page = $params['page'] ?? 1;
        $pageSize = $params['pageSize'] ?? 10;
        $where = [];

        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . trim($params['name']) . '%'];
        }

        if (isset($params['status']) && $params['status'] !== '') {
            $where[] = ['status', '=', $params['status']];
        }

        $result = $this->memberVip->where($where)
            ->order(['sort' => 'desc','updated_at'=>'desc', 'id' => 'desc'])
            ->paginate([
                'list_rows' => $pageSize,
                'page' => $page
            ])->append(['status_text']);

        return $result;
    }

    /**
     * 创建会员VIP等级
     *
     * @param array $param 会员VIP数据
     * @return MemberVip
     */
    public function save($param)
    {
        if(isset($param['id'])) unset($param['id']);
        return $this->memberVip->allowField(['name','remark', 'discount',  'status', 'sort'])->create($param);
    }

    /**
     * 更新会员VIP等级
     *
     * @param int $id 会员VIP ID
     * @param array $param 更新数据
     * @return bool
     */
    public function update($id, $param)
    {
        $memberVip = $this->memberVip->find($id);
        if (!$memberVip) {
            return false;
        }

        return $memberVip->allowField(['name','remark', 'discount',  'status', 'sort'])->save($param);
    }

    /**
     * 删除会员VIP等级
     *
     * @param int $id 会员VIP ID
     * @return bool
     */
    public function delete($id)
    {
        return $this->memberVip->destroy($id);
    }

    /**
     * 获取会员VIP详情
     *
     * @param int $id 会员VIP ID
     * @return MemberVip|null
     */
    public function detail($id)
    {
        return $this->memberVip->find($id);
    }

    /**
     * 获取所有可用的会员VIP等级
     *
     * @return array
     */
    public function getAll()
    {
        if (isset($param['status']) && $param['status'] !== '') {
            $where[] = ['status', '=', 1];
            return $this->memberVip->where($where)
                ->order(['sort' => 'desc', 'id' => 'asc'])
                ->field('name,id')
                ->select();
        } else {
            return $this->memberVip->order(['sort' => 'desc', 'id' => 'asc'])
                ->withTrashed()
                ->field('name,id')
                ->select();
        }
    }
}
